package com.swiftops.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.swiftops.common.model.TokenModel;
import com.swiftops.common.model.User;
import com.swiftops.common.service.TokenService;
import com.swiftops.common.util.IdGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class IdTokenServiceImpl implements TokenService {

    @Value("${app.jwtExpirationInMinutes:120}") // 设置默认值为120分钟
    private int jwtExpirationInMinutes;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public TokenModel createToken(User user) {
        //使用转换后的分钟数计算过期时间
        Date expiryDate = DateUtils.addMinutes(new Date(), jwtExpirationInMinutes);
        String tokenId = String.format("token_%s_%s", user.getUsername(), IdGen.next());
        TokenModel model = new TokenModel(tokenId, "", user);
        model.setTokenId(tokenId);
        model.setExpiryTime(expiryDate.getTime());

        stringRedisTemplate.opsForValue().set(tokenId, JSON.toJSONString(model), jwtExpirationInMinutes, TimeUnit.MINUTES);
        return model;
    }

    @Override
    public TokenModel refreshToken(String refreshToken) {
        return null;
    }

    @Override
    public boolean checkToken(TokenModel model) {
        if (model == null) return false;
        String token = model.getToken();
        Boolean hasKey = stringRedisTemplate.hasKey(token);
        return hasKey;
    }

    @Override
    public TokenModel getTokenModel(String token) {
        if (StringUtils.isBlank(token)) return null;
        String userJson = stringRedisTemplate.opsForValue().get(token);
        TokenModel tokenModel = JSON.parseObject(userJson, TokenModel.class);
        return tokenModel;
    }

    @Override
    public boolean deleteToken(String token) {
        if (StringUtils.isBlank(token)) return false;
        //
        Boolean delete = stringRedisTemplate.delete(token);
        return delete;
    }
}
